<script>
import DB, { copyDB, checkDB } from '@/utils/sqlite.js';

export default {
	globalData: {
		dbReady: false,       // 是否已初始化数据库
		dbInitPromise: null,  // 初始化Promise，防止重复初始化
	},

	methods: {
		/**
		 * 初始化数据库
		 */
		async initDatabase() {
			if (this.globalData.dbInitPromise) return this.globalData.dbInitPromise;

			this.globalData.dbInitPromise = (async () => {
				try {
					await checkDB();
					console.log('✅ 数据库文件已存在');
				} catch (e) {
					console.log('📦 数据库不存在，正在复制...');
					await copyDB();
					console.log('✅ 数据库复制成功');
				}

				// 只有未打开时才 open
				if (!DB.isOpen()) {
					await DB.open();
					console.log('✅ 数据库已打开');
				} else {
					console.log('ℹ️ 数据库已处于打开状态');
				}

				this.globalData.dbReady = true;
				return true;
			})();

			return this.globalData.dbInitPromise;
		},

		/**
		 * 等待数据库准备好
		 */
		async waitForDBReady() {
			if (this.globalData.dbReady) return true;
			if (this.globalData.dbInitPromise) return this.globalData.dbInitPromise;
			return this.initDatabase();
		},
	},

	async onLaunch() {
		console.log('🚀 App Launch');
		await this.initDatabase();
	},

	async onShow() {
		console.log('👀 App Show');

		if (!this.globalData.dbReady) {
			console.log('⏳ 数据库未初始化，重新初始化中...');
			await this.initDatabase();
		} else {
			console.log('✅ 数据库已准备好');
		}
	},

	onHide() {
		console.log('🚪 App Hide');
		try {
			DB.close();
			console.log('🔒 数据库连接已关闭');
			this.globalData.dbReady = false;
			this.globalData.dbInitPromise = null;
		} catch (err) {
			console.warn('⚠️ 数据库关闭时出现问题：', err.message);
		}
	},
};
</script>

<style lang="scss">
@import "@/uni_modules/uview-plus/index.scss";
</style>
